<?php

namespace App\Http\Controllers\Api\V1;

use App\Interfaces\PictureService;
use App\Models\Picture;
use Illuminate\Http\Request;
use App\Exceptions\Api\ApiDoneErrorException;
use App\Exceptions\Api\ApiInputErrorException;
use App\Exceptions\Api\ApiRsaEecryptErrorException;
use App\Exceptions\Api\ApiUserNotLoginErrorException;
use App\Exceptions\Api\ApiValidateErrorException;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Symfony\Component\HttpFoundation\Response;
use App\Services\OSS;

class FileUploadController extends Controller
{

    public function fileUpload(Request $request,PictureService $pictureService){

        $file_name = $request->get('file_name');
        $file_content = $request->get('file_content');
        if($file_name==''){
            throw new ApiInputErrorException('缺少请求参数file_name');
        }
        if($file_content==''){
            throw new ApiInputErrorException('缺少请求参数file_content');
        }

        $file_type = explode(".",$file_name)[1];
        $id = md5(uniqid(mt_rand(), true));
        $newFileName = $id.'.'.$file_type;
        $file_content = base64_decode($file_content);
        $return = OSS::uploadContent($newFileName, $file_content); // 上传一个文件
        if ($return){
            //插入数据库
            Picture::create([
                'id'=>$id,
                'file_path'=>$newFileName,
                'file_name'=>$file_name,
                'file_ext'=>$file_type,

            ]);
        }


        $json = [
            'success'=>true,
            'name'=>$file_name,
            'id'=>$id,
            'url'=>$pictureService::thumb($id),
            'file_path'=>$pictureService::thumb($id)
        ];
        return Response()->json($json);
    }

}
